// pages/form/index.js
const app=getApp();
const keys=['channel','concatAccess','caseType','caseCategory','resourceType','resourceLevel'];
let dictCache={};
Page({
  data: {
    channelObjs: ['渠道1', '渠道2', '渠道3'],
    channels: ['渠道1', '渠道2', '渠道3'],
    channelIndex: 0,
    channelValue:'',
    channelAccount: '',
    clientNickname: '',
    sourceObjs: ['渠道1', '渠道2', '渠道3'],
    sources: ['来源1', '来源2', '来源3'],
    sourceIndex: 0,
    sourceValue:'',
    phone: '',
    wechat: '',
    caseCategoryObjs:[],
    caseCategories: ['A','B','D','F'],
    caseCategoryIndex:0,
    caseCategoryValue:'',
    allCaseTypeObjs:[],
    caseTypeObjs:[],
    caseTypes: ['类型1', '类型2', '类型3'],
    caseTypeIndex: 0,
    caseTypeValue:'',
    remark: '',

    formats: {},
    readOnly: false,
    placeholder: '开始输入备注...',
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false
  },
onLoad:function(options){
  const platform = wx.getSystemInfoSync().platform
  const isIOS = platform === 'ios'
  this.setData({
    isIOS
  })
},
  // 渠道选择
  bindChannelChange(e) {
    this.setData({ channelIndex: e.detail.value ,channelValue:this.data.channels[e.detail.value]});
  },

  // 渠道账号输入
  onChannelAccountInput(e) {
    this.setData({ channelAccount: e.detail.value });
  },

  // 客户昵称输入
  onClientNicknameInput(e) {
    this.setData({ clientNickname: e.detail.value });
  },

  // 来源方式选择
  bindSourceChange(e) {
    this.setData({ sourceIndex: e.detail.value,sourceValue: this.data.sources[ e.detail.value] });
  },

  // 手机号输入
  onPhoneInput(e) {
    this.setData({ phone: e.detail.value });
  },

  // 微信输入
  onWechatInput(e) {
    this.setData({ wechat: e.detail.value });
  },

  // 案件大类选择
  bindCaseCategoryChange(e) {
    const allCaseTypeObjs=this.data.allCaseTypeObjs;
    const caseCategoryValue=this.data.caseCategoryObjs[e.detail.value].value;
    const caseTypeObjs= allCaseTypeObjs
    .filter(p=>p.value.startsWith(caseCategoryValue));
    const caseTypes= caseTypeObjs.map(p=>p.label);
    this.setData({ caseCategoryIndex: e.detail.value ,caseCategoryValue:caseCategoryValue
      ,caseTypeObjs: caseTypeObjs
      ,caseTypes:caseTypes,caseTypeValue:'',caseTypeIndex:0});
  },
 
  // 案件类型选择
  bindCaseTypeChange(e) {
    this.setData({ caseTypeIndex: e.detail.value,caseTypeValue:this.data.caseTypes[e.detail.value] });
  },

  // 备注输入
  onRemarkInput(e) {
    this.setData({ remark: e.detail.value });
  },

  // 提交表单
  submitForm: async function() {
    const content=await this.geteditcontent();
    console.log("提交的备注:",content);
    this.setData({remark:content});
    const formData = {
      channel: this.data.channelObjs[this.data.channelIndex].value,
      channelAccount: this.data.channelAccount,
      nickname: this.data.clientNickname,
      concatAccess: this.data.sourceObjs[this.data.sourceIndex].value,
      phone: this.data.phone,
      wechat: this.data.wechat,
      caseCategory: this.data.caseCategoryObjs[this.data.caseCategoryIndex].value,
      caseType: this.data.caseTypeObjs[this.data.caseTypeIndex].value,
      content: content
    };

    console.log('提交数据:', formData);
    // 这里可以调用 API 提交数据
    this.add(formData,(data)=>{
      wx.showToast({
        title: '保存成功',
        icon: 'none',
        duration: 2000
      });
    });
  },
  onShow: async function () {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const options = currentPage.options;
  
    try {
      // 1. 加载字典
      const dictMap = await this.loadDictCached(keys);
      this.initPage(dictMap);
    } catch (error) {
      console.error('页面加载失败:', error);
    }
  },
  initPage:function(dictMap){
    const channelDictItems=dictMap['channel'];
    const channels= channelDictItems.map((v)=> v.label);

    const sourceObjs=dictMap['concatAccess'];
    const sources= sourceObjs.map((v)=> v.label);

    const caseCategoryObjs=dictMap['caseCategory'];
    const caseCategories= caseCategoryObjs.map((v)=> v.label);
    const allCaseTypeObjs=dictMap['caseType'];
    
    this.setData({channelObjs:channelDictItems,channels:channels
                ,sourceObjs:sourceObjs,sources:sources
                ,caseCategoryObjs:caseCategoryObjs,caseCategories:caseCategories
                ,allCaseTypeObjs:allCaseTypeObjs});
  }, 

// ✅ 带缓存的 loadDict
loadDictCached:function(keys) {
  const cacheKey = keys.sort().join(','); // 用 keys 排序后作为缓存 key

  // 1. 如果已缓存，直接返回
  if (dictCache[cacheKey]) {
    return Promise.resolve(dictCache[cacheKey]);
  }

  // 3. 第一次加载，发起请求
  const promise = new Promise((resolve, reject) => {
    app.request.post('/sysDict/loadByKeys', [...keys], (res) => {
      if (res.code === 0) {
        dictCache[cacheKey] = res.data; // ✅ 缓存数据
        resolve(res.data);
      } else {
        wx.showToast({ title: res.msg, icon: 'none' });
        reject(new Error(res.msg));
      }
    }, (err) => {
      wx.showToast({ title: '网络连接失败', icon: 'none' });
      reject(err);
    });
  });

  return promise;
},
 // loadDict 返回 Promise
loadDict(keys) {
  return new Promise((resolve, reject) => {
    app.request.post('/sysDict/loadByKeys', [...keys], (res) => {
      if (res.code === 0) {
        resolve(res.data);
      } else {
        wx.showToast({ title: res.msg, icon: 'none' });
        reject(new Error(res.msg));
      }
    }, (err) => {
      wx.showToast({ title: '网络连接失败', icon: 'none' });
      reject(err);
    });
  });
},
  
  add:function(payload,callback){
     
    app.request.post('/customer', payload, (res) => {
      console.log('保存数据返回:', res);
      if(res.code ===0){
        // 这里设置data里这个枚举的数组
        callback(res.data);
      }else{
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        });
      }     
    },(err)=>{
      wx.showToast({
        title: '网络连接失败',
        icon: 'none',
        duration: 2000
      });
    });
  },


  undo() {
    this.editorCtx.undo();
  },
  redo() {
    this.editorCtx.redo();
  },
  //分割线
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    });
  },
  // 移除样式
  removeFormat() {
    this.editorCtx.removeFormat();
  },
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const {
      statusBarHeight,
      platform
    } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
      /*注释部分为获取上一页的富文本字符串到本页，通过setContents初始化编辑器内容 */
      // let pages = getCurrentPages()
      // let pre = pages[pages.length - 2]
      // let {
      //   ofunction
      // } = pre.data
      // console.log(recruitinfo);
      // if (!recruitinfo.ofunction) {
      //   return
      // }
      // that.editorCtx.setContents({
      //   html: ofunction
      // })

    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    console.log(e);
    console.log('format', name, value)
    if (!name) return
    this.editorCtx.format(name, value)

  },
  geteditcontent:async function () {
    return new Promise((resolve, reject) => {
      this.editorCtx.getContents({
        success: ({
          html,
          text,
          delta
        }) => {
          console.log(html, 'success');
          resolve(html);         
        },
        fail: error => {
          console.log(error);
          reject(error);
        }
      })
    })
  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
    console.log(e);
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        /* 一下注释部分为上传到服务器并将的服务器图片真实地址存放到富文本中*/
        const uploadUrl= app.baseUrl+'/sysFiles/upload';
        console.log("开始上传文件到服务器",app.request.host, uploadUrl, res.tempFilePaths[0]);
        wx.uploadFile({
          url: uploadUrl, // 服务器上传图片地址
          filePath: res.tempFilePaths[0],
          header: {
            "Content-Type": "multipart/form-data"
          },
          name: 'file',
          formData: {
            name: 'file'
          },
          success: (ress) => {
            // this.setData({})}
            console.log('图片上传结果返回', ress);
            if(ress.statusCode===200 && ress.data){
              const respBody= app.util.parseJsonObject(ress.data);
              if(respBody.code===0){
                console.log('上传后的图片地址:',respBody.data);
                that.editorCtx.insertImage({
                   src: respBody.data,  
                   width: '80%',
                  success: function () {
                    console.log('insert image success')
                  }
                })
              }
            }
          }
        })
      }
    })
  },
  insertRemark:function(e){
    const that = this;
    that.setData({remark:"<p><span style=\"color: rgba(2, 2, 8, 0.87); font-family: system-ui, -apple-system, 'Segoe UI', Roboto, Ubuntu, Cantarell, 'Noto Sans', sans-serif, BlinkMacSystemFont, 'Helvetica Neue', Arial, 'PingFang SC', 'PingFang TC', 'PingFang HK', 'Microsoft Yahei', 'Microsoft JhengHei'; font-size: 14px; white-space-collapse: preserve; background-color: #ffffff;\">你好，我想咨询一下全屋定制家具的纠纷，对方不能按时交付和安装货物，我想退货退款并申请赔偿，对方之前是签了赔偿协议的，但是现在拖着我，导致我一直无法继续装修和入住。我该怎么办？我是申请法院立案还是调解比较快？</span></p>    <p>&nbsp;</p>    <p><span style=\"color: rgba(2, 2, 8, 0.87); font-family: system-ui, -apple-system, 'Segoe UI', Roboto, Ubuntu, Cantarell, 'Noto Sans', sans-serif, BlinkMacSystemFont, 'Helvetica Neue', Arial, 'PingFang SC', 'PingFang TC', 'PingFang HK', 'Microsoft Yahei', 'Microsoft JhengHei'; font-size: 14px; white-space-collapse: preserve; background-color: #ffffff;\">电话沟通全屋定制金额17w 11w客户缴费的费用还有6万是赔偿协议的赔偿金额对方拖了客户2年左右。客户诉求是咨询诉讼费用不想委托处理不愿意委托律师处理想自己走小程序起诉不愿意走非诉。</span></p>"
    });
    const { remark } = this.data;
    
    if (!that.editorCtx || !remark) {
      wx.showToast({
        title: '暂无内容可反显',
        icon: 'none'
      });
      return;
    }
    
    // 设置富文本内容
    that.editorCtx.setContents({
      html: remark,
      success: () => {
        wx.showToast({
          title: '反显成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        console.error('反显内容失败', err);
        wx.showToast({
          title: '反显失败',
          icon: 'none'
        });
      }
    });
  }
});
